package nlp;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import control.ProcessedInput;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.parser.lexparser.LexicalizedParser;
import edu.stanford.nlp.process.CoreLabelTokenFactory;
import edu.stanford.nlp.process.PTBTokenizer;
import edu.stanford.nlp.process.TokenizerFactory;
import edu.stanford.nlp.trees.Tree;

public class NLP {
	
	public ProcessedInput getKeywords(String sentence) {
		String input = "";
		String questionWord = "";
		List<String> keyword = new ArrayList<String>();

		input = sentence;

		LexicalizedParser lp = LexicalizedParser
				.loadModel("edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz");

		TokenizerFactory<CoreLabel> tokenizerFactory = PTBTokenizer.factory(
				new CoreLabelTokenFactory(), "");
		List<CoreLabel> rawWords = tokenizerFactory.getTokenizer(
				new StringReader(sentence)).tokenize();
		Tree parse = lp.apply(rawWords);

		switch (parse.firstChild().value().toString()) {
		case "SQ":
			questionWord = parse.firstChild().firstChild().getChild(0).value();
			break;

		case "SBARQ":
			Tree wh = parse.firstChild().firstChild().firstChild();
			if (!wh.value().toString().equals("WHNP")) {
				Tree temp = parse.firstChild().firstChild();
				questionWord = temp.getChild(0).getChild(0).value().toString();
				if (temp.numChildren() > 1) {
					questionWord += " "
							+ temp.getChild(1).getChild(0).value().toString();
				}
			} else {
				questionWord = wh.getChild(0).getChild(0).value().toString()
						+ " " + wh.getChild(1).getChild(0).value().toString();
			}
			break;

		default:
			break;
		}

		for (Tree t : parse.getLeaves()) {
			String type = parse.pathNodeToNode(t, parse.firstChild()).get(1)
					.value().toString();
			if (type.charAt(0) == 'N' || type.charAt(0) == 'J') {
				keyword.add(t.toString());
			}

		}

//		ProcessedInput pi = new ProcessedInput(input, questionWord, keyword);
		ProcessedInput pi = new ProcessedInput();
		return pi;
	}
	public String getBestAnswer(List<String> answer) {
		return null;
	}

	// singleton
	private static NLP instance = null;

	protected NLP() {

	}

	public static NLP getInstance() {
		if (null == instance) {
			instance = new NLP();
		}
		return instance;
	}
	
}
